/**
 * 获取数据类型
 * @param {*} val
 * @returns
 */
module.exports.getType = (val) => {
  const type = Object.prototype.toString.call(val)
  let resType = ""
  switch (type) {
    case "[object String]":
      resType = "String"
      break
    case "[object Number]":
      resType = "Number"
      break
    case "[object Boolean]":
      resType = "Boolean"
      break
    case "[object Array]":
      resType = "Array"
      break
    case "[object Object]":
      resType = "Object"
      break
    case "[object Function]":
      resType = "Function"
      break
    case "[object Null]":
      resType = "Null"
      break
    case "[object Undefined]":
      resType = "undefined"
      break
  }
  return resType
}

/**
 * 获取对象的所有key
 * @param {Object} obj
 * @returns
 */
module.exports.getKeysSql = (obj = {}) => {
  return Object.keys(obj).join(",")
}

// 获取对象所有的values
module.exports.getValuesSql = (obj = {}) => {
  const { getType } = module.exports
  const keys = Object.keys(obj)
  const valueArr = keys.map((k) => {
    const v = obj[k]
    if (getType(v) === "String") {
      return `'${v}'`
    }
    return v
  })
  return valueArr.join(",")
}

// 获取对象key、value，返回key = value
module.exports.getKeyMapValue = (obj = {}) => {
  const { getValueOfKey } = module.exports
  const keys = Object.keys(obj)
  const arr = keys.map((k) => {
    const v = getValueOfKey(obj, k, "quotation")
    return `${k} = ${v}`
  })
  return arr.join(", ")
}

// 获取对象的字段值
// type: quotation 字符串类型的值添加引号''
module.exports.getValueOfKey = (data, key, type) => {
  if (!data || !key) return
  const v = data[key]
  let value = ""
  if (type === "quotation") {
    const kType = module.exports.getType(v)
    value = kType === "String" ? `'${v}'` : v
  } else {
    value = v
  }
  return value
}

/**
 * 返回简单的where查询语句，用and拼接, 并去除pageSize, pageNum参数
 * {key1: 'aa', key2: 'bb'} 返回 key1 = 'aa' AND key2 = 'bb'
 * @param {Object} data
 * @returns
 */
module.exports.whereAndSql = (data) => {
  const { getType, getKeys, getValueOfKey } = module.exports
  const exclude = ["pageSize", "pageNum"]
  if (!data || getType(data) !== "Object") return

  const keys = getKeys(data)
  const key_Sqls = keys
    .map((k) => {
      if (exclude.includes(k)) {
        return false
      }
      const value = getValueOfKey(data, k) // 获取字段值
      return `${k} = '${value}'`
    })
    .filter((v) => v)
  const sql = key_Sqls.join(" AND ")
  return sql
}

/**
 * 根据页码、每页条数获取截取信息
 * @param {Number} pageNum 页码
 * @param {Number} pageSize 每页条数
 * @returns
 */
module.exports.pageLimit = (pageNum, pageSize) => {
  const { getType } = module.exports
  if (getType(pageNum) !== "Number") pageNum = 1
  if (getType(pageSize) !== "Number") pageSize = 0
  const s = (pageNum - 1) * pageSize
  const n = pageSize
  return [s, n]
}
